# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import urllib

from directory import Directory
import fsentry

MFDataType = {
    'Uninitialized' : 0,
    'Text' : 1,
    'Integer' : 2,
    'Floating' : 3,
    'Date' : 5,
    'Time' : 6,
    'Timestamp' : 7,
    'Boolean' : 8,
    'Lookup' : 9,
    'MultiSelectLookup' : 10,
    'Integer64' : 11,
    'Filetime' : 12,
    'MultiLineText' : 13,
    'ACL' : 14
}

def text_escape(t):
    escapes = {
        'a' : '*',
        'p' : ' ',
        'u' : '_',
        '%' : 'p',
        '.' : 's',
        '\'' : 'q'
    }

    return re.sub(
        '_(.)', 
        lambda m : escapes.get(m.group(1)),
        urllib.quote(t))
    

foldertypes = {
    MFDataType['Integer'] : 'I',
    MFDataType['Floating'] : 'F',


    # Date is represented as "JavaScript ticks"?
    MFDataType['Date'] : 'D',
    MFDataType['Time'] : 'C',
    MFDataType['Timestamp'] : 'P',

    # Texts need escaping
    MFDataType['Text'] : { 'key' : 'T', 'func' : lambda item : text_escape(item['Value']) },
    MFDataType['MultiLineText'] : { 'key' : 'M', 'func' : lambda item : text_escape(item['Value']) },

    MFDataType['Lookup'] : 
        { 'key' : 'L', 'func' : lambda item : item['Lookup']['Item'] },
    MFDataType['Boolean'] :
        { 'key' : 'B', 'func' : lambda item : item['Lookup']['Item'] and 'true' or 'false' }
}

class PropertyFolder(Directory):
    """
    Property folder (aka. virtual folder) inside a view.
    """

    def __init__(self, parent, iteminfo):
        Directory.__init__(self, parent, iteminfo)

    def get_name(self):
        # TODO: Figure out the real escape pattern
        return self.iteminfo['DisplayValue'].replace('/', '_')

    def get_urlname(self):
        foldertype = foldertypes[self.iteminfo['DataType']]
        if type(foldertype) == str:
            return foldertype + str(self.iteminfo['Value'])
        elif type(foldertype) == dict:
            return foldertype['key'] + str(foldertype['func'](self.iteminfo))
        else:
            raise TypeError


